package errors

import (
	"context"
	"github.com/go-kratos/kratos/v2/middleware"
)

type HandlerFunc func(ctx context.Context, req interface{}, err error) error

type Option func(*options)

type options struct {
	handler HandlerFunc
}

func WithHandler(h HandlerFunc) Option {
	return func(o *options) {
		o.handler = h
	}
}

func Errors(opts ...Option) middleware.Middleware {
	op := options{
		handler: func(ctx context.Context, req interface{}, err error) error {
			return err
		},
	}
	for _, o := range opts {
		o(&op)
	}
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			reply, err = handler(ctx, req)
			if err == nil {
				return
			}
			err = op.handler(ctx, req, err)
			return
		}
	}
}
